package KK.System.IO
{ 
	import KK.System.System;
	
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	
	import mx.core.Singleton;

	public class File extends EventDispatcher
	{
		private var state:int;
		static private const OPEN:int=0;
		static private const SAVE:int=1;
		
		static private var _instance:File;
		
		private var _file:FileReference;
		public function File(single:Singleton)
		{
			if(_instance){
				throw new Error("this singleton class pless using Instance get Instance");
			}
			_instance=this;
			init();
		}
		
		/**
		 * 初始化  
		 * 
		 */
		private function init():void{
			_file=new FileReference();
			_file.addEventListener(Event.SELECT,onHandler);
			_file.addEventListener(Event.COMPLETE,onHandler); 
		}
		  
		/**
		 * 选择框 
		 * @param event
		 * 
		 */
		private function onHandler(event:Event):void{
			if(state==SAVE)
			{
				return;
			}
			switch(event.type){
				case Event.SELECT:
					_file.load();
					break;
				case Event.COMPLETE:
					ReadByte();
					break;
			}
		}
		
		/**
		 * 读取数据  
		 * @return 
		 * 
		 */
		private function ReadByte():ByteArray{
			var result:ByteArray=_file.data;
			
			dispatchEvent(new FileEvent(FileEvent.FILE_LOADED,_file.data));
			
			return result;
		}
		/**
		 * 保存数据  
		 * @param bytes
		 * 
		 */
		private function save(bytes:ByteArray):void{
			state=SAVE;
			_file.save(bytes,"mapData.dat");
		}
		
		/**
		 *	打开  
		 * 
		 */
		private function open(filter:Array=null):void{
			state=OPEN;
			_file.browse(filter);
		}
		
		/**
		 * 保存  
		 * @param bytes
		 * 
		 */
		static public function Save(bytes:ByteArray):void{
			
			Instance.save(bytes);
		}
		 
		
		/**
		 * 打开对象 
		 * 
		 */
		static public function Open(filter:Array=null):void{
			Instance.open(filter);
		}
		
		/**
		 * 获取单例  
		 * @return 
		 * 
		 */
		static public function  get Instance():File{
			if(!_instance){
				new File(new Singleton);
			}
			return _instance;
		}
	}
}


class Singleton{
	
}